package com.xiang.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

public class NetUtils {
	/**
	 * 获取json
	 * @param urlPath
	 * @return
	 * @throws Exception
	 */
	public static  String getJsonString(String urlPath) throws Exception {  
        URL url = new URL(urlPath);  
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
        connection.connect();  
        InputStream inputStream = connection.getInputStream();  
        //对应的字符编码转换  
        Reader reader = new InputStreamReader(inputStream, "UTF-8");  
        BufferedReader bufferedReader = new BufferedReader(reader);  
        String str = null;  
        StringBuffer sb = new StringBuffer();  
        while ((str = bufferedReader.readLine()) != null) {  
            sb.append(str);  
        }  
        reader.close();  
        connection.disconnect();  
        return sb.toString();  
    }
	/**
	 * 获取lrc地址
	 * @param urlPath
	 * @return
	 */
	public static  String getlrc(String urlPath) {
		String lrcStr = null;
		try {
			lrcStr =  jsonToObj(getJsonString(urlPath));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lrcStr;
	}
	/**
	 * 解析json
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static String jsonToObj(String jsonStr) throws Exception {  
		String lrcStr = null;
        JSONObject jsonObject = new JSONObject(jsonStr);  
        JSONArray result= jsonObject.getJSONArray("result");  
        int length = result.length();  
        for (int i = 0; i < length; i++) {  
            jsonObject = result.getJSONObject(i);  
            lrcStr = jsonObject.getString("lrc"); 
        }
		return lrcStr;  
    }  
}
